<template>
  <a-upload
    :file-list="fileList"
    :before-upload="beforeUpload"
    :remove="handleFileRemove"
    @change="handleChange"
    accept=".doc,.docx"
  >
    <a-button v-if="!isShow">
      <a-icon type="upload"/>
      上传文件
    </a-button>
  </a-upload>
</template>

<script>
  import {uploadAction, deleteAction} from '@/api/manage'

  export default {
    name: "ZUpload",
    props: ['fileData', 'isShow'],
    data() {
      return {
        saveFiles: "/sys/common/templateUpload",
        removeFilse: '/xtsz/sjWordTemplate/removeFile',
        fileList: [
          // {
          //   uid: '-1',
          //   name: 'xxx.png',
          //   status: 'done',
          //   url: 'http://www.baidu.com/xxx.png',
          // },
        ],
      };
    },
    watch: {
      fileData: {
        handler: function (val) {
          if (val.fileName) {
            this.fileList = [{
              uid: val.id,
              name: val.fileName,
              status: 'done',
              url: `${window._CONFIG['domianURL']}/sys/common/download${val.tempUrl}`,
            }]
          }
        },
        immediate: true
      }
    },

    methods: {
      beforeUpload() {
        return false
      },
      handleChange(info) {
        let fileList = [...info.fileList];
        if (fileList.length > 1) {
          this.$message.error('只能上传一个文件，请删除后在上传！')
        } else {
          fileList = fileList.map(file => {
            if (file.response) {
              file.url = file.response.url;
            }
            return file;
          });
          this.fileList = fileList;
        }
      },
      saveFile() {
        const {fileList} = this;
        if (fileList.length > 0) {
          let formData = new FormData()
          fileList.forEach(file => {
            if (file.originFileObj) {
              formData.append('files', file.originFileObj)
            }
          })
          uploadAction(this.saveFiles, formData).then((res) => {
            if (res.success) {
              this.$emit('uploadFile', res.result);
            } else {
              this.$emit('uploadFile', null);
            }
          })
        } else {
          this.$emit('uploadFile', null);
        }
      },
      handleFileRemove(file) {
        console.log(file)
        if (file.status) {
          deleteAction(this.removeFilse, {id: file.uid}).then((res) => {
            if (res.success) {
              this.$message.success(res.message)
              return true
            } else {
              this.$message.error(res.message)
              return false
            }
          })
        } else {
          return true
        }

      }
    },
  }
</script>

<style lang="less" scoped>

</style>